<?php
/**
 * 维修记录审批相关接口请求参数验证器
 * Created by PhpStorm.
 * User: LRChang
 * Date: 2018/5/30
 * Time: 15:22
 * Mail: hjklrchang@qq.com
 */

namespace app\adminapi\validate;

use app\base\exception\ParamException;
use app\base\validate\BaseValidate;
use think\Validate;

class MaintenanceApproveValidate extends BaseValidate
{
    protected $rule = [
        'page' => 'isPositiveInt',
        'pagenum' => 'isPositiveInt',
//        'fields' => '',
        'where_json' => 'isWhereJson',

        'approve_id' => 'require|isPositiveInt',
        'maintenance_record_id' => 'require|isPositiveInt',
        'company_id' => 'require|isPositiveInt',
        'company_name' => 'require|max:100',
        'car_id' => 'require|isPositiveInt',
        'plate_no' => 'require|max:50',
        'maintenance_id' => 'require|isPositiveInt',
        'maintenance_name' => 'require|max:100',
        'contact_person' => 'require|max:20',
        'contact_number' => 'require|number|min:11|max:15',
        'maintenance_time' => 'require|dateFormat:Y-m-d H:i:s',
        'kilometers' => 'require|>=:0',
        'maintenance_desc' => 'max:255',
        'remark' => 'max:255',
        'material_cost_info' => 'require|checkCostInfo',
        'working_hours' => 'require|checkWorkingHours',
        'material_cost_total' => '>=:0',
        'working_hours_total' => '>=:0',
        'maintenance_total' => '>=:0',
        'approve_person' => 'require|max:20',
        'approve_orgn' => 'require|max:100',
        'approve_time' => 'require|dateFormat:Y-m-d H:i:s',
        'approve_status' => 'require|in:1,2,3,4',
        'approve_desc' => 'max:255',

        'approve_ids' => 'require|checkIDs',
    ];

    // 默认值
    protected $default = [
        'page' => 1,
        'pagenum' => 20,
        'where_json' => '',
        'fields' => '*',
    ];

    protected $message = [
        'page.isPositiveInt' => '页数只能为正整数',
        'pagenum.isPositiveInt' => '每页数量只能为正整数',
        'fields.isNotEmpty' => '字段不能为空',
        'where_json.isWhereJson' => '不是合法的json字符串',
        'material_cost_info.checkCostInfo' => '不为空时必须为json数组字符串',
        'working_hours.checkWorkingHours' => '不为空时必须为json数组字符串',
        'approve_ids.checkIDs' => "approve_id 必须为正整数，多个请用','号连接"
    ];

    protected $scene = [
        'list' => ['page' ,'pagenum', 'fields', 'where_json'],
        'add' => [
            'maintenance_record_id',
            'company_id',
//            'car_id',
            'maintenance_id',
            'contact_person',
            'contact_number',
            'maintenance_time',
            'kilometers',
            'maintenance_desc',
            'remark',
            'material_cost_info',
            'working_hours',
            'material_cost_total',
            'working_hours_total',
            'approve_person',
            'approve_orgn',
            'approve_status',
            'approve_desc',
        ],
        'edit' => [
            'approve_id',
            'maintenance_record_id',
            'company_id',
//            'car_id',
            'maintenance_id',
            'contact_person',
            'contact_number',
            'maintenance_time',
            'kilometers',
            'maintenance_desc',
            'remark',
            'material_cost_info',
            'working_hours',
            'material_cost_total',
            'working_hours_total',
            'approve_person',
            'approve_orgn',
            'approve_status',
            'approve_desc',
        ],
        'delete' => [ 'approve_ids' ],
    ];

    /**
     * 验证材料费用
     * @param $value
     * @return bool
     * @throws ParamException
     */
    protected function checkCostInfo($value){
        if(!$this->isJsonString($value)) return false;
        $value = json_decode($value, true);

        // 当传入空值时，替换为空数组
        if(empty($value)){
            $this->replaceData('material_cost_info', []);
            $this->replaceData('material_cost_total', 0);
            return true;
        }

        if(!is_array($value)) return false;

        $allowKeys = ['material_name', 'material_type', 'supplier', 'tel', 'num', 'unit', 'price', 'total'];
        $material_cost_total = 0;
        foreach ($value as &$arr){
            if(!is_array($arr) || empty($arr) || count($arr) !== count($allowKeys)){
                throw new ParamException('material_cost_info 的子元素属性必须包含且只能包含“' . implode(',', $allowKeys) . '”中的每一项');
            }

            $validate = new Validate([
                'material_name' => 'require|max:100',
                'material_type' => 'max:100',
                'supplier' => 'max:100',
                'tel' => 'number|min:11|max:15',
                'unit' => 'max:10',
                'num' => 'require|float|>:0',
                'price' => 'require|float|>=:0',
            ]);

            if(!$validate->check($arr)){
                throw new ParamException('material_cost_info 中' . $validate->getError());
            }

            // 统计此项总价
            $arr['total'] = $arr['num'] * $arr['price'];
            $material_cost_total += $arr['total'];
        }

        $this->replaceData('material_cost_info', $value);
        $this->replaceData('material_cost_total', $material_cost_total);
        return true;
    }

    /**
     * 验证工时费用
     * @param $value
     * @return bool
     * @throws ParamException
     */
    protected function checkWorkingHours($value){
        if(!$this->isJsonString($value)) return false;
        $value = json_decode($value, true);

        // 当传入空值时，替换为空数组
        if(empty($value)){
            $this->replaceData('working_hours', []);
            $this->replaceData('working_hours_total', 0);
            return true;
        }

        if(!is_array($value)) return false;

        $allowKeys = ['working_name', 'price', 'hour', 'total'];
        $working_hours_total = 0;
        foreach ($value as &$arr){
            if(!is_array($arr) || empty($arr) || count($arr) !== count($allowKeys)){
                throw new ParamException('working_hours 的子元素属性必须包含且只能包含“' . implode(',', $allowKeys) . '”中的每一项');
            }

            $validate = new Validate([
                'working_name' => 'require|max:100',
                'hour' => 'require|float|>:0',
                'price' => 'require|float|>=:0',
            ]);

            if(!$validate->check($arr)){
                throw new ParamException('working_hours 中' . $validate->getError());
            }

            // 统计此项总价
            $arr['total'] = $arr['hour'] * $arr['price'];
            $working_hours_total += $arr['total'];
        }

        $this->replaceData('working_hours', $value);
        $this->replaceData('working_hours_total', $working_hours_total);
        return true;
    }
}